import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login.vue'
import Home from '@/views/Home.vue'
import Welcome from '@/views/Welcome'
import Users from '@/views/User'
import Rights from '@/views/Rights'
import Roles from '@/views/Roles'
import Goods from '@/views/Goods'
import Params from '@/views/Params'
import Categories from '@/views/Categories'
import Orders from '@/views/Orders'
import Reports from '@/views/Reports'
Vue.use(VueRouter)

const routes = [
  {
    // 路由重定向
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/home',
    redirect: '/welcome',
    component: Home,
    children: [{
      path: '/welcome',
      name: 'Welcome',
      component: Welcome
    }, {
      path: '/users',
      name: 'Users',
      component: Users
    }, {
      path: '/rights',
      name: 'Rights',
      component: Rights
    }, {
      path: '/roles',
      name: 'Roles',
      component: Roles
    }, {
      path: '/goods',
      name: 'Goods',
      component: Goods
    },
    {
      path: '/params',
      name: 'Params',
      component: Params
    },
    {
      path: '/categories',
      name: 'categories',
      component: Categories
    },
    {
      path: '/orders',
      name: 'Orders',
      component: Orders
    },
    {
      path: '/reports',
      name: 'Reports',
      component: Reports
    }
    ]
  }

]

const router = new VueRouter({
  routes
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数，表示放行
  //   next() 放行 nex('/login') 强制跳转
  if (to.path === '/login') return next()
  // 获取token
  const tokenStr = window.sessionStorage.getItem('Token')
  // 没有token，强制跳转到登录页
  if (!tokenStr) return next('/login')
  next()
})

export default router
